﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using KZ.Utilities;
using KZ.Express.H.ENT;
using KZ.Express.H.Presenter;
using KZ.Express.H.BLL;

namespace KZ.Express.H.Settings.Zones
{
    public partial class ZoneDetailView : BaseView
    {
        #region Fields

        object _previousValue;
        List<ZoneDetailENT> _changedRow;

        #endregion Fields

        #region Private Methods

        private void ZoneDetailView_Load(object sender, EventArgs e)
        {
            _changedRow = new List<ZoneDetailENT>();
            LoadData();
        }

        private void dtgZoneDetail_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
        {
            e.Control.PreviewKeyDown -= Control_PreviewKeyDown;
            e.Control.PreviewKeyDown += Control_PreviewKeyDown;
        }

        private void dtgZoneDetail_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                e.SuppressKeyPress = true;
                if (dtgZoneDetail.CurrentCell.ColumnIndex == colTemp.Index)
                {
                    if (dtgZoneDetail.CurrentRow.Index == dtgZoneDetail.RowCount - 1)
                        base.AddRow();
                    dtgZoneDetail.CurrentCell = dtgZoneDetail[colCountryName.Index, dtgZoneDetail.CurrentCell.RowIndex + 1];
                }
                else if (dtgZoneDetail.CurrentCell.RowIndex == dtgZoneDetail.RowCount - 1)
                {
                    SendKeys.Send("{tab}");
                }
                else
                {
                    SendKeys.Send("{tab}");
                    SendKeys.Send("{up}");
                }
            }
        }

        private void dtgZoneDetail_CellEnter(object sender, DataGridViewCellEventArgs e)
        {
            if (!dtgZoneDetail.CurrentCell.ReadOnly)
                dtgZoneDetail.BeginEdit(true);
        }

        private void dtgZoneDetail_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
        {
            _previousValue = dtgZoneDetail[e.ColumnIndex, e.RowIndex].Value;
        }

        private void dtgZoneDetail_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            if (_previousValue != dtgZoneDetail[e.ColumnIndex, e.RowIndex].Value)
            {
                DataRow[] rows = this.Table.Select("CountryID = " + dtgZoneDetail[colCountryID.Index, e.RowIndex].Value);
                if (rows.Length > 0)
                {
                    ZoneDetailENT zoneDetail = new ZoneDetailENT();
                    zoneDetail.ZoneID = this.EntityID;
                    zoneDetail.Zone = Utility.StringParse(rows[0]["Zone"]);
                    zoneDetail.CountryID = Utility.IntParse(rows[0]["CountryID"]);
                    zoneDetail.CreatedBy = UserENT._USERID;
                    zoneDetail.UpdatedBy = UserENT._USERID;

                    int index;
                    if ((index = _changedRow.FindIndex(p => p.CountryID == zoneDetail.CountryID)) == -1)
                        _changedRow.Add(zoneDetail);
                    else
                        _changedRow[index].Zone = zoneDetail.Zone;
                }
            }
        }

        private void Control_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                if (dtgZoneDetail.CurrentCell.ColumnIndex == colZone.Index ||
                    dtgZoneDetail.CurrentCell.ColumnIndex == colTemp.Index)
                {
                    if (dtgZoneDetail.CurrentRow.Index == dtgZoneDetail.RowCount - 1)
                    {
                        base.AddRow();
                        dtgZoneDetail.CurrentCell = dtgZoneDetail[colCountryName.Index, dtgZoneDetail.CurrentCell.RowIndex + 1];
                        dtgZoneDetail_CellEnter(dtgZoneDetail, new DataGridViewCellEventArgs(colCountryName.Index, dtgZoneDetail.CurrentCell.RowIndex + 1));
                    }
                    else
                        dtgZoneDetail.CurrentCell = dtgZoneDetail[colCountryName.Index, dtgZoneDetail.CurrentCell.RowIndex];
                }
                else if (dtgZoneDetail.CurrentRow.Index == dtgZoneDetail.RowCount - 1)
                {
                    SendKeys.Send("{tab}");
                }
                else
                {
                    SendKeys.Send("{tab}");
                    SendKeys.Send("{up}");
                }
            }
        }

        private void LoadData()
        {
            try
            {
                _changedRow.Clear();
                _presenter.LoadDataTable<ZoneDetailENT>();
                switch (this.ActionName)
                {
                    case "Insert":
                        break;

                    case "Update":
                        int zoneCount = this.Table.AsEnumerable().
                            Where(p => !String.IsNullOrEmpty(p.Field<string>("Zone"))).
                            GroupBy(p => p["Zone"]).Count();
                        lblZoneCount.Text = "Số zone: " + zoneCount;
                        _presenter.LoadEntity<ZoneENT>();
                        break;
                }
            }
            catch (BusinessLogicException ex)
            {
                ShowMessageBoxError(ex.Message);
            }
        }

        #endregion Private Methods

        #region Constructors

        public ZoneDetailView()
        {
            InitializeComponent();
            Initialize(dtgZoneDetail);

            _presenter = new BasePresenter(this, new ZoneBLL());

            this.ObjectID = (int)Objects.Zone;
            this.dtgZoneDetail.Sorted += new EventHandler(Datagrid_Sorted);
        }

        #endregion Constructors

        #region Public Properties

        [Search]
        public int ZoneID
        {
            get { return base.EntityID; }
        }

        public override BaseENT Entity
        {
            get
            {
                ZoneENT zone = new ZoneENT();
                zone.ZoneID = base.EntityID;
                zone.ZoneCode = txtZoneCode.Text;
                zone.ZoneName = txtZoneName.Text;
                zone.CreatedBy = UserENT._USERID;
                zone.UpdatedBy = UserENT._USERID;
                zone.ZoneDetails = _changedRow;

                zone.ValidateData();

                return zone;
            }
            set
            {
                ZoneENT zone = value == null ? new ZoneENT() : value as ZoneENT;
                txtZoneCode.Text = zone.ZoneCode;
                txtZoneName.Text = zone.ZoneName;
            }
        }

        #endregion Public Properties

        #region Public Methods

        public override void Save()
        {
            try
            {
                dtgZoneDetail.EndEdit();
                _presenter.Save();
                _changedRow.Clear();
            }
            catch (BusinessLogicException ex)
            {
                ShowMessageBoxError(ex.Message);
            }
        }

        #endregion Public Methods
    }
}
